package com.study.crypto.gb.server.config;

import com.study.crypto.gb.server.entity.Certification;
import com.study.crypto.gb.server.entity.KeyStorage;
import com.study.crypto.gb.server.mapper.CertificationMapper;
import com.study.crypto.gb.server.mapper.KeyStorageMapper;
import com.study.crypto.utils.KeyUtils;
import lombok.Getter;
import lombok.Setter;
import org.bouncycastle.asn1.x509.Certificate;
import org.bouncycastle.pqc.legacy.math.linearalgebra.ByteUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.security.PrivateKey;

/**
 * @author Songjin
 * @since 2021-06-07 0:28
 */
@Getter @Setter
@Component
public class EnvironmentConfig implements ApplicationListener<WebServerInitializedEvent>, InitializingBean {

    /** 服务启动时使用的端口号 */
    private int port;
    private String httpUrl;
    
    private Certification certification;
    private KeyStorage    keyStorage;
    private Certificate   certificate;
    private PrivateKey    privateKey;
    
    private Certification publishCertification;
    private KeyStorage    publishKeyStorage;
    private Certificate   publishCertificate;
    private PrivateKey    publishPrivateKey;
    
    @Autowired
    private CertificationMapper certificationMapper;
    @Autowired
    private KeyStorageMapper keyStorageMapper;
    
    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        this.port = event.getWebServer().getPort();
        this.httpUrl = "http://127.0.0.1:" + port;
    }
    
    @Override
    public void afterPropertiesSet() throws Exception {
        Certification gomainQuery = Certification.builder().ext1("Gomain").build();
        certification = certificationMapper.selectOne(gomainQuery);
        certificate = Certificate.getInstance(certification.getCertificate());
        keyStorage = keyStorageMapper.selectByPrimaryKey(certification.getKeyId());
        privateKey = KeyUtils.convertPrivateKey(ByteUtils.subArray(keyStorage.getKeyBytes(), 64));
    
        this.publishCertification = certification;
        this.publishKeyStorage = keyStorage;
        this.publishCertificate = certificate;
        this.publishPrivateKey = privateKey;
    }
    
}
